package com.cyj.mongodbsign.cyj.controller;

import com.cyj.mongodbsign.cyj.model.ResultFormat;
import com.cyj.mongodbsign.cyj.pojo.Student;
import com.cyj.mongodbsign.cyj.service.StudentService;
import com.cyj.mongodbsign.cyj.util.EasyPoiUtils;
import com.cyj.mongodbsign.cyj.util.ResultUtil;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 签到
     * @param studentName
     * @return
     */
    @PostMapping("sign")
    @ResponseBody
    public ResultFormat home(String studentName){
        UpdateResult student = studentService.studentSgin(studentName);
        return ResultUtil.success("签到成功", student);
    }


    @GetMapping("/studentList")
    @ResponseBody
    public Map getAllStudent(){
        Map map = new HashMap();
        try {
            List<Student> signStudent = studentService.getStudentBySign(true);
            List<Student> noSignStudent = studentService.getStudentBySign(false);
            System.out.println("signStudent:"+signStudent);
            System.out.println("noSignStudent:"+noSignStudent);
            map.put("code",200);
            map.put("signStudent",signStudent);
            map.put("noSignStudent",noSignStudent);
            map.put("msg","查找学生成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",400);
            map.put("msg","查找学生失败");
        }
        return map;
    }

    /**
     * 从表格插入数据
     *
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/uploadExcel")
    @ResponseBody
    public ResultFormat uploadExcel(@RequestParam("file") MultipartFile file) throws IOException {

        List<Student> studentList = EasyPoiUtils.importExcel(file, Student.class);
        for (Student students : studentList) {
            mongoTemplate.insert(students, "students");
        }

        return ResultUtil.success(studentList);
    }



}
